package com.cos.hospital.ui.usercenter;

import android.view.View;
import android.widget.GridView;

import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.init.BaseActivity;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.bean.user.SchBean;
import com.cos.hospital.model.bean.user.SchDefaultBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.UDialog;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.ui.usercenter.adapter.SchGridWeekAdapter;
import com.cos.hospital.widget.ProgressDialog;
import com.google.gson.JsonObject;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * @Description: 默认排班
 * @Author: Kosmos
 * @Date: 2018年09月15日 23:52
 * @Email: KosmoSakura@foxmail.com
 */
public class SchedulingDefaultActivity extends BaseActivity {
    @BindView(R.id.sch_gv)
    GridView gv;
    private SchGridWeekAdapter adapter;
    //    private List<SchBean> list;
    private SchBean[] list = new SchBean[32];
    private int[] schs = new int[7];

    @Override
    protected int layout() {
        return R.layout.activity_scheduling_default;
    }

    @Override
    protected void init() {
        setTitleLeftIcon();
        setTitleCenterTxt(getString(R.string.my_scheduling_default));
        setTitleRightTxt(getString(R.string.save));
        adapter = new SchGridWeekAdapter(list, context);
        gv.setAdapter(adapter);
    }

    /**
     * 1.默认排班以周为单位，点击排班情况即可修改排班；
     * 2.默认排班修改保存后，将重置今日所在周下一周及以后的所有排班情况；
     */
    @Override
    protected void logic() {
        gv.setOnItemClickListener((parent, view, position, id) -> {
            if (position >= 0 && position < list.length && list[position] != null) {
                if (list[position].getType() == SchGridWeekAdapter.T_SELECT) {
                    list[position].setSelect(!list[position].isSelect());
                    adapter.setSelectPosition(position);
                    adapter.notifyDataSetChanged();
                }
            }
        });
        ProgressDialog.getInstance().startProgressDialog(this);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("id", SPUtil.getUserId());
        UHttp.start(getServes().getScheduleDefault(jsonObject), "默认排班查询", new HttpMsgListener<ResultBean<SchDefaultBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                ProgressDialog.getInstance().stopProgressDialog();
                showNotice(describe);
            }

            @Override
            public void onSuccess(ResultBean<SchDefaultBean> dto) {
                if (dto.isSuccess()) {
                    SchDefaultBean result = dto.getResult();
                    if (result == null) {
                        showNotice("数据异常");
                        ProgressDialog.getInstance().stopProgressDialog();
                        return;
                    }
                    schs[0] = result.getFldMonday();
                    schs[1] = result.getFldTuesday();
                    schs[2] = result.getFldWednesday();
                    schs[3] = result.getFldThursday();
                    schs[4] = result.getFldFriday();
                    schs[5] = result.getFldSaturday();
                    schs[6] = result.getFldSunday();
                    initAWeek();
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
        initFrame();
    }

    /**
     * 绘制边框
     */
    private void initFrame() {
        list[0] = new SchBean(SchGridWeekAdapter.T_CLASS, "排班");
        list[8] = new SchBean(SchGridWeekAdapter.T_CLASS, "上午");
        list[16] = new SchBean(SchGridWeekAdapter.T_CLASS, "下午");
        list[24] = new SchBean(SchGridWeekAdapter.T_CLASS, "晚上");
        String[] weeks = new String[]{"一", "二", "三", "四", "五", "六", "日"};
        for (int i = 0; i < weeks.length; i++) {
            list[i + 1] = new SchBean(SchGridWeekAdapter.T_WEEK, weeks[i]);
            initMark(schs[i], i + 1);//先添加空事件,防止崩溃
        }
        adapter.notifyDataSetChanged();
    }

    private void initAWeek() {
        for (int point = 0; point < 7; point++) {
            initMark(schs[point], point + 1);
        }
        ProgressDialog.getInstance().stopProgressDialog();
        adapter.notifyDataSetChanged();
    }

    /**
     * @param position 位置
     * @param select   是否排班
     */
    private void inputSelect(int position, boolean select) {
        list[position] = new SchBean(SchGridWeekAdapter.T_SELECT, select, true);
    }

    /**
     * @param point 位置
     * @param mark  0是无排班， 1是早上排班， 2是下午排班， 3是晚上，
     *              4是早上＋下午， 5是早上＋晚上，6是下午＋晚上，7是全天（早中晚）
     */
    private void initMark(int mark, int point) {
        switch (mark) {
            case 0:
                inputSelect(point + 8, false);
                inputSelect(point + 16, false);
                inputSelect(point + 24, false);
                break;
            case 1:
                inputSelect(point + 8, true);
                inputSelect(point + 16, false);
                inputSelect(point + 24, false);
                break;
            case 2:
                inputSelect(point + 8, false);
                inputSelect(point + 16, true);
                inputSelect(point + 24, false);
                break;
            case 3:
                inputSelect(point + 8, false);
                inputSelect(point + 16, false);
                inputSelect(point + 24, true);
                break;
            case 4:
                inputSelect(point + 8, true);
                inputSelect(point + 16, true);
                inputSelect(point + 24, false);
                break;
            case 5:
                inputSelect(point + 8, true);
                inputSelect(point + 16, false);
                inputSelect(point + 24, true);
                break;
            case 6:
                inputSelect(point + 8, false);
                inputSelect(point + 16, true);
                inputSelect(point + 24, true);
                break;
            case 7:
                inputSelect(point + 8, true);
                inputSelect(point + 16, true);
                inputSelect(point + 24, true);
                break;
        }
    }

    @OnClick({R.id.title_back, R.id.title_next_txt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.title_next_txt:
                save();
                break;
        }
    }

    private void save() {
        String[] fldSchs = new String[]{"fldMonday", "fldTuesday", "fldWednesday", "fldThursday", "fldFriday", "fldSaturday", "fldSunday"};
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldDoctorId", SPUtil.getUserId());
        for (int i = 0; i < fldSchs.length; i++) {
            jsonObject.addProperty(fldSchs[i], checkSchResult(list[i + 9].isSelect(), list[i + 17].isSelect(), list[i + 25].isSelect()));
        }
        ProgressDialog.getInstance().startProgressDialog(this, "保存中");
        UHttp.start(getServes().getScheduleDefaultSave(jsonObject), "默认排班保存", new HttpMsgListener<ResultBean>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean dto) {
                if (dto.isSuccess()) {
                    UDialog.getInstance(context, false, false)
                        .showNoticeWithOnebtn("默认排班修改成功!", (result, dia) -> finish());
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    /**
     * @param morning 早上是否排班
     * @param noon    中午排班情况
     * @param night   晚上排班情况
     * @return 0是无排班， 1是早上排班， 2是下午排班， 3是晚上，
     * 4是早上＋下午， 5是早上＋晚上，6是下午＋晚上，7是全天（早中晚）
     */
    private int checkSchResult(boolean morning, boolean noon, boolean night) {
        if (morning && noon && night) {
            return 7;
        } else if (morning && noon) {
            return 4;
        } else if (morning && night) {
            return 5;
        } else if (noon && night) {
            return 6;
        } else if (morning) {
            return 1;
        } else if (noon) {
            return 2;
        } else if (night) {
            return 3;
        } else {
            return 0;
        }
    }
}
